﻿using Station.Common.Rejudgment;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Station.Inspect
{
    public partial class FormRejudg : Form
    {
        public Project Prj { get; set; }
        public ErrList ErrLst { get; set; }
        //private List<ErrCell> ErrCells = new List<ErrCell>();
        private List<Object> ErrCells = new List<Object>();
        private int Index = -1;
        private bool bCheckAll = false;

        //ErrCell cell;
        Object cell;
        ErrComponent comp;
        Font font;
        public FormRejudg()
        {
            InitializeComponent();
            this.TopMost = true;
        }
        //
        protected override void WndProc(ref Message m)
        {
            GlobalHotKey.OnHotKeyPressed(m);
            base.WndProc(ref m);
            const int WM_HOTKEY = 0x0312;
            switch (m.Msg)
            {
                case WM_HOTKEY:
                    switch (m.WParam.ToInt32())
                    {
                        case 1000:
                            Console.WriteLine("∧");
                            if (ErrCells.Count > 0 && Index > 0)
                            {
                                Index--;
                                UpdateInfo();
                            }
                            break;
                        case 1001:
                            Console.WriteLine("∨");
                            GetNext();
                            break;
                        case 1002:
                            Console.WriteLine("←");
                            if (ErrCells.Count > 0)
                            {
                                Index = 0;
                                UpdateInfo();
                            }
                            break;
                        case 1003:
                            Console.WriteLine("→");
                            if (ErrCells.Count > 0)
                            {
                                Index = ErrCells.Count - 1;
                                UpdateInfo();
                                this.button2.Enabled = true;
                                this.button1.Enabled = true;
                            }
                            break;
                        case 1004:
                            Console.WriteLine("0");
                            if (ErrCells.Count > 0)
                            {
                                Object item = ErrCells[Index];
                                if (item is ErrCell)
                                {
                                    ErrCell errCell = item as ErrCell;
                                    errCell.Status = CellStatus.NG;
                                }
                                else if (item is ErrComponent)
                                {
                                    ErrComponent errComp = item as ErrComponent;
                                    errComp.Status = CellStatus.NG;
                                }
                                GetNext();
                            }
                            break;
                        case 1005:
                            Console.WriteLine("1");
                            if (ErrCells.Count > 0)
                            {
                                Object item = ErrCells[Index];
                                if (item is ErrCell)
                                {
                                    ErrCell errCell = item as ErrCell;
                                    errCell.Status = CellStatus.OK;
                                }
                                else if (item is ErrComponent)
                                {
                                    ErrComponent errComp = item as ErrComponent;
                                    errComp.Status = CellStatus.OK;
                                }
                                GetNext();
                            }
                            break;
                        case 1006:
                            Console.WriteLine("enter");
                            this.Close();
                            break;
                        // 更多case...
                        default:
                            Console.WriteLine($"{m.WParam.ToInt32()}");
                            break;
                    }
                    break;
            }
        }
        private void FormRejudg_Load(object sender, EventArgs e)
        {

            new GlobalHotKey(this.Handle, ((int)GlobalHotKey.Hotkeys.Hotkey1), GlobalHotKey.KeyModifiers.None, Keys.Up);
            new GlobalHotKey(this.Handle, ((int)GlobalHotKey.Hotkeys.Hotkey2), GlobalHotKey.KeyModifiers.None, Keys.Down);
            new GlobalHotKey(this.Handle, ((int)GlobalHotKey.Hotkeys.Hotkey3), GlobalHotKey.KeyModifiers.None, Keys.Left);
            new GlobalHotKey(this.Handle, ((int)GlobalHotKey.Hotkeys.Hotkey4), GlobalHotKey.KeyModifiers.None, Keys.Right);
            new GlobalHotKey(this.Handle, ((int)GlobalHotKey.Hotkeys.Hotkey5), GlobalHotKey.KeyModifiers.None, Keys.N);
            new GlobalHotKey(this.Handle, ((int)GlobalHotKey.Hotkeys.Hotkey6), GlobalHotKey.KeyModifiers.None, Keys.M);
            new GlobalHotKey(this.Handle, ((int)GlobalHotKey.Hotkeys.Hotkey7), GlobalHotKey.KeyModifiers.None, Keys.Enter);
            //
            this.button2.Enabled = false;
            this.button1.Enabled = false;
            this.label_allpass.Visible = false;
            //--------
            StaInspect.Instance.IsPass = false;
            StaInspect.Instance.RecheckClose = false;
            StaInspect.Instance.IsBaofei = false;
            ucPreView1.Paint += UcPreView1_Paint;
            StaInspect.Instance.RejudgEvent.Reset();

            foreach (var item in ErrLst.ErrLibComponents)
            {
                ErrCells.Add(item);
            }

            foreach (var comp in ErrLst.ErrComponents)
            {
                foreach (var item in comp.ErrCells)
                {
                    if (item.Status == CellStatus.OK)
                    {
                        ErrCells.Add(item);
                    }
                }
            }
            if (ErrCells.Count > 0)
            {
                Index = 0;
            }
            else
            {
                this.label_allpass.Visible = true;
                StaInspect.Instance.IsPass = true;
            }
            //
            StaInspect.Instance.passcount = 0;
            StaInspect.Instance.goodcount = 0;
            StaInspect.Instance.checkcount = 0;
            StaInspect.Instance.defectcount = 0;
            font = new Font("微软雅黑", 20);
            ucSketch.AddImg(Prj.sketchImg);
            ucSketch.AutoSizeImage();
            UpdateInfo();
            //OnFirst();
            StaInspect.Instance.IsCheckOpen = true;
            if (StaInspect.Instance.IsMarkBaofei)
            {
                Close();
            }

        }


        private void UcPreView1_Paint(object sender, PaintEventArgs e)
        {
            var g = e.Graphics;
            //float scale = (float)StaInspect.Instance.Prj.sketchProp;
            float prop = (float)(ucPreView1.ScaleCur);
            g.TranslateTransform(ucPreView1.ImgOrgInPic.X, ucPreView1.ImgOrgInPic.Y);
            g.ScaleTransform(prop, prop);
            if (comp != null)
            {
                foreach (var item in comp.ErrCells)
                {
                    if (item != cell)
                    {
                        int cx = (item.Rect.Left + item.Rect.Right) / 2;
                        int cy = (item.Rect.Top + item.Rect.Bottom) / 2;
                        g.DrawRectangle(Pens.LightGreen, item.Rect);
                        g.DrawLine(Pens.Yellow, cx - 20, cy, cx + 20, cy);
                        g.DrawLine(Pens.Yellow, cx, cy - 20, cx, cy + 20);
                        g.DrawString($"{item.ID}", font, Brushes.Yellow, cx + 10, cy + 10);
                    }
                }
            }
            //ErrCell curCell = cell as ErrCell;
            //if(cell !=null)
            //if (curCell != null)
            if (cell is ErrCell)
            {
                ErrCell curCell = cell as ErrCell;
                int cx = (curCell.Rect.Left + curCell.Rect.Right) / 2;
                int cy = (curCell.Rect.Top + curCell.Rect.Bottom) / 2;
                g.DrawRectangle(Pens.Red, curCell.Rect);
                g.DrawLine(Pens.Yellow, cx - 20, cy, cx + 20, cy);
                g.DrawLine(Pens.Yellow, cx, cy - 20, cx, cy + 20);
                g.DrawString($"{curCell.ID}", font, Brushes.Yellow, cx + 10, cy + 10);
                foreach (var item in curCell.RectErrs)
                {
                    g.DrawRectangle(Pens.Red, item.rect);
                    if (string.IsNullOrEmpty(item.Name) == false)
                    {
                        g.DrawString(item.Name, font, Brushes.Red, item.rect.Right + 10, item.rect.Bottom - 10);
                    }
                }
            }
            else if (cell is ErrComponent)
            {
                ErrComponent curComp = cell as ErrComponent;
                foreach (var item in curComp.RectErrs)
                {
                    g.DrawRectangle(Pens.Red, item.rect);
                    if (string.IsNullOrEmpty(item.Name) == false)
                    {
                        g.DrawString(item.Name, font, Brushes.Red, item.rect.Right + 10, item.rect.Bottom - 10);
                    }
                }
            }

        }
        Pen pen = new Pen(Color.Green, 10);
        SolidBrush brush = new SolidBrush(Color.FromArgb(50, 0, 255, 0));
        private void ucSketch_Paint(object sender, PaintEventArgs e)
        {
            var g = e.Graphics;
            float scale = (float)Prj.sketchProp;
            float prop = (float)(ucSketch.ScaleCur * scale);
            g.TranslateTransform(ucSketch.ImgOrgInPic.X, ucSketch.ImgOrgInPic.Y);
            g.ScaleTransform(prop, prop);
            foreach (var comp in Prj.Components)
            {
                foreach (var item in comp.Elements)
                    item.Draw(g, scale);
            }
            //if (cell !=null)
            if (cell is ErrCell)
            {
                ErrCell curCell = cell as ErrCell;
                //cell.Pos
                g.DrawLine(pen, curCell.Pos.X - 10 / scale, curCell.Pos.Y, curCell.Pos.X + 10 / scale, curCell.Pos.Y);
                g.DrawLine(pen, curCell.Pos.X, curCell.Pos.Y - 10 / scale, curCell.Pos.X, curCell.Pos.Y + 10 / scale);
                g.FillEllipse(brush, curCell.Pos.X - 50 / scale, curCell.Pos.Y - 50 / scale, 100 / scale, 100 / scale);
            }
            else if (cell is ErrComponent)
            {
                ErrComponent curCell = cell as ErrComponent;
                var rect = curCell.GetRect();
                float x = rect.Left + rect.Width / 2;
                float y = rect.Top + rect.Height / 2;
                g.DrawLine(pen, x - 10 / scale, y, x + 10 / scale, y);
                g.DrawLine(pen, x, y - 10 / scale, x, y + 10 / scale);
                g.FillEllipse(brush, x - 50 / scale, y - 50 / scale, 100 / scale, 100 / scale);
            }
            //if (StaInspect.Instance.CurBmpPt != null)
            //{
            //    var centerPt = StaInspect.Instance.CurBmpPt.point;
            //    int lineLen = 100;
            //    g.DrawRectangle(Pens.Yellow, (centerPt.X - 2048), (centerPt.Y - 1500), 4096, 3000);
            //    g.DrawLine(Pens.Yellow, centerPt.X - lineLen, centerPt.Y, centerPt.X + lineLen, centerPt.Y);
            //    g.DrawLine(Pens.Yellow, centerPt.X, centerPt.Y - lineLen, centerPt.X, centerPt.Y + lineLen);
            //}
        }
        void UpdateInfo()
        {
            ucPreView1.ClearImg();
            ucLib.ClearImg();
            //ucPreView1.ClearDrawObject();
            cell = null;
            comp = null;
            if (Index >= 0 && Index < ErrCells.Count)
            {
                cell = ErrCells[Index];

            }
            tbIndex.Text = $"{Index + 1}/{ErrCells.Count}";
            if (cell is ErrCell)
            {
                ErrCell errCell = cell as ErrCell;
                comp = ErrLst.ErrComponents.First(p => p.ErrCells.Contains(errCell));
                ucPreView1.AddImg(comp.Image);
                ucPreView1.AutoSizeImage();
                if (comp.Lib != null && comp.Lib.Image != null)
                {
                    ucLib.AddImg(comp.Lib.Image);
                    ucLib.AutoSizeImage();
                }
                tbPcs.Text = $"{comp.MarkID}";
                tbLib.Text = $"{comp.Lib?.ID}";
                tbID.Text = $"{errCell.ID}";
                tbRes.Text = errCell.RectErrs.Max(p => p.Score).ToString();
            }
            else if (cell is ErrComponent)
            {
                comp = cell as ErrComponent;
                tbPcs.Text = $"{comp.MarkID}";
                tbLib.Text = $"{comp.Lib?.ID}";
                tbID.Text = $"";
                tbRes.Text = comp.RectErrs.Max(p => p.Score).ToString();
                ucPreView1.AddImg(comp.Image);
                ucPreView1.AutoSizeImage();
                if (comp.Lib != null && comp.Lib.Image != null)
                {
                    ucLib.AddImg(comp.Lib.Image);
                    ucLib.AutoSizeImage();
                }
            }
            else
            {
                tbPcs.Text = "";
                tbLib.Text = "";
                tbID.Text = "";
                tbRes.Text = "";
            }
            btnSave.Enabled = bCheckAll;
            ucPreView1.Invalidate();
            ucLib.Invalidate();
            ucSketch.Invalidate();
        }

        void GetNext()
        {
            if (ErrCells.Count > 0)
            {
                if (Index == ErrCells.Count - 1)
                {
                    bCheckAll = true;
                }
                else
                {
                    Index++;
                }
                UpdateInfo();
            }

        }

        private void btnFirst_Click(object sender, EventArgs e)
        {
            if (ErrCells.Count > 0)
            {
                Index = 0;
                UpdateInfo();
            }
        }
        private void btnLast_Click(object sender, EventArgs e)
        {
            if (ErrCells.Count > 0)
            {
                Index = ErrCells.Count - 1;
                UpdateInfo();
                this.button2.Enabled = true;
                this.button1.Enabled = true;
            }
        }

        private void btnPreve_Click(object sender, EventArgs e)
        {
            if (ErrCells.Count > 0 && Index > 0)
            {
                Index--;
                UpdateInfo();
            }
        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            GetNext();
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            if (ErrCells.Count > 0)
            {
                Object item = ErrCells[Index];
                if (item is ErrCell)
                {
                    ErrCell errCell = item as ErrCell;
                    errCell.Status = CellStatus.OK;
                }
                else if (item is ErrComponent)
                {
                    ErrComponent errComp = item as ErrComponent;
                    errComp.Status = CellStatus.OK;
                }
                GetNext();
            }
        }

        private void btnNG_Click(object sender, EventArgs e)
        {
            if (ErrCells.Count > 0)
            {
                Object item = ErrCells[Index];
                if (item is ErrCell)
                {
                    ErrCell errCell = item as ErrCell;
                    errCell.Status = CellStatus.NG;
                }
                else if (item is ErrComponent)
                {
                    ErrComponent errComp = item as ErrComponent;
                    errComp.Status = CellStatus.NG;
                }
                GetNext();
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            //ErrLst.Save();
            this.Close();
        }

        private void FormRejudg_FormClosed(object sender, FormClosedEventArgs e)
        {
            int ngcount = 0;//不良
            int passcount = 0;//直通
            int okcount = 0;//过检率
            int goodcount = 0;//良
            if (ErrCells.Count > 0)
            {
                for (int i = 0; i < ErrCells.Count; i++)
                {
                    Object item = ErrCells[i];
                    if (item is ErrComponent)
                    {
                        ErrComponent errComp = item as ErrComponent;
                        if (errComp.Status == CellStatus.NG)
                        {
                            StaInspect.Instance.IsBaofei = true;
                            StaInspect.Instance.doChangeBaoFei(true);
                            break;
                        }

                    }
                    if (item is ErrCell)
                    {
                        ErrCell errCell = item as ErrCell;
                        if (errCell.Status == CellStatus.NG)
                        {
                            ngcount++;

                        }
                        if (errCell.Status == CellStatus.PASS)
                        {
                            passcount++;
                            goodcount++;
                        }
                        if (errCell.Status == CellStatus.OK)
                        {
                            okcount++;
                            goodcount++;
                        }

                    }
                }

                StaInspect.Instance.passcount = passcount;
                StaInspect.Instance.goodcount = okcount;
                StaInspect.Instance.checkcount = goodcount;
                StaInspect.Instance.defectcount = ngcount;


                if (ngcount >= StaInspect.Instance.CellNGCount)
                {
                    if (StaInspect.Instance.IsCellNGMax)
                    {
                        StaInspect.Instance.IsBaofei = true;
                    }

                }
            }
            StaInspect.Instance.RecheckClose = true;
            StaInspect.Instance.AddErrLst(ErrLst);
            StaInspect.Instance.RejudgEvent.Set();

        }


        private void button2_Click(object sender, EventArgs e)
        {

            if (ErrCells.Count > 0)
            {
                for (int i = 0; i < ErrCells.Count; i++)
                {
                    Object item = ErrCells[i];
                    if (item is ErrCell)
                    {
                        ErrCell errCell = item as ErrCell;
                        errCell.Status = CellStatus.OK;
                    }
                    else if (item is ErrComponent)
                    {
                        ErrComponent errComp = item as ErrComponent;
                        errComp.Status = CellStatus.OK;
                    }
                }
                btnSave.Enabled = true;
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {

            if (ErrCells.Count > 0)
            {
                for (int i = 0; i < ErrCells.Count; i++)
                {
                    Object item = ErrCells[i];
                    if (item is ErrCell)
                    {
                        ErrCell errCell = item as ErrCell;
                        errCell.Status = CellStatus.NG;
                    }
                    else if (item is ErrComponent)
                    {
                        ErrComponent errComp = item as ErrComponent;
                        errComp.Status = CellStatus.NG;
                    }
                }
                btnSave.Enabled = true;
            }
        }
    }
}
